package cn.itcast.controller;


import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.entity.Result;
import cn.itcast.pojo.User;
import cn.itcast.pojo.UserInfo;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.List;


@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Reference
    private UserService userService;


    //获得当前登录用户的用户名
    @GetMapping("/getUsername")
    public Result getUsername(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        //这里的user不是pojo的user,而是springsecurity中的
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(userInfo);
        if(userInfo != null){
            String username = userInfo.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }



    /**
     * 查询用户管理列表
     * @param queryPageBean 查询条件
     * @return
     */
    @GetMapping("page")
    public Result findPage(QueryPageBean queryPageBean){
        try {
            System.out.println("userService = " + userService);
            PageResult pageResult = userService.findPage(queryPageBean);
            System.out.println("pageResult--" + pageResult);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, pageResult);
        } catch (Exception e) {
            log.error("查询用户管理列表失败", e);
        }
        return new Result(false, MessageConstant.QUERY_USER_FAIL);
    }


    /**
     * 新增用户
     * @param roleIds 角色id集合
     * @param user 用户信息
     * @return
     */
    @PreAuthorize("hasAuthority('USER_ADD')")
    @PostMapping
    public Result handleAdd(int[] roleIds, @RequestBody User user){
        try {
            Boolean flag = userService.handleAdd(roleIds, user);
            if (flag){
                return new Result(true, MessageConstant.ADD_USER_SUCCESS, flag);
            }
        } catch (Exception e) {
            log.error("新增用户失败", e);
        }
        return new Result(false, MessageConstant.ADD_USER_FAIL);
    }




    /**
     * 根据id查询用户信息
     * @param id 用户id
     * @return
     */
    @PreAuthorize("hasAuthority('USER_QUERY')")
    @GetMapping("{id}")
    public Result findUserById(@PathVariable("id") Integer id){
        try {
            User user = userService.findUserById(id);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
        } catch (Exception e) {
            log.error("查询用户管理列表失败", e);
        }
        return new Result(false, MessageConstant.QUERY_USER_FAIL);
    }


    /**
     * 根据id查询用户角色
     * @param id 用户id
     * @return
     */
    @PreAuthorize("hasAuthority('USER_QUERY')")
    @GetMapping("{id}/roleIds")
    public Result findRoleById(@PathVariable("id") Integer id){
        try {
            List<Integer> list = userService.findRoleById(id);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS, list);
        } catch (Exception e) {
            log.error("查询用户管理列表失败", e);
        }
        return new Result(false, MessageConstant.QUERY_USER_FAIL);
    }




    /**
     * 编辑用户
     * @param roleIds 角色id集合
     * @param user 用户信息
     * @return
     */
    //@PreAuthorize("hasAuthority('USER_EDIT')")
    @PutMapping
    public Result handleEdit(int[] roleIds, @RequestBody User user){
        try {
            Boolean flag = userService.handleEdit(roleIds, user);
            if (flag){
                return new Result(true, MessageConstant.EDIT_USER_SUCCESS, flag);
            }
        } catch (Exception e) {
            log.error("编辑用户失败", e);
        }
        return new Result(false, MessageConstant.EDIT_USER_FAIL);
    }



    /**
     * 根据id删除用户
     * @param id  用户id
     * @return
     */
    @PreAuthorize("hasAuthority('USER_DELETE')")
    @DeleteMapping("{id}")
    public Result handleDelete(@PathVariable("id") Integer id){
        try {
            Boolean flag = userService.handleDelete(id);
            if (flag){
                return new Result(true, MessageConstant.DELETE_USER_SUCCESS, flag);
            }
        } catch (Exception e) {
            log.error("根据id删除菜单失败", e);
        }
        return new Result(false, MessageConstant.DELETE_USER_FAIL);
    }


}
